package com.woniu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.entity.dto.RegisterDTO;
import com.woniu.entity.dto.UserLoginDTO;
import com.woniu.mapper.UserMapper;
import com.woniu.pojo.User;
import com.woniu.service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author xiaotang
 * @since 2023-07-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 1. 先根据用户名查找用户
        User user = userMapper.getByUsername(userLoginDTO.getUsername());
        if(user == null){
            return null;
        }
        // 2. 如果存在，在匹配密码
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(userLoginDTO.getPassword(), user.getPassword());
        if(!matches){
            return null;
        }
        return user;
    }

    @Override
    public User getByUsername(String token) {
        return userMapper.getByUsername(token);
    }

    @Override
    public Boolean register(RegisterDTO registerDTO)throws Exception {
        // 1. 判断手机号码是否被注册，如果被注册了，提示并返回
        User user = getUserByMobile(registerDTO.getMobile());
        if(user != null){
            throw new Exception("手机号码已经被注册");
        }
        // 2. 如果没有注册，填充必要的属性，调用mapper保存数据即可
        user = new User();
        user.setMobile(registerDTO.getMobile());
        user.setUsername(registerDTO.getMobile());
        userMapper.insert(user);
        // 3. 返回结果
        return true;
    }

    private User getUserByMobile(String mobile) {
        return userMapper.getUserByMobile(mobile);
    }
}